<?php


namespace app\common\cachemodel;


use app\common\model\BaseCache;
use think\Env;
use think\Log;
use XznsTools\cache\CacheManage;

class ZlFeedbackQuestion extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl_feedback_question';

    protected $cacheModel = 'feedback.question';

    protected $cacheIdKey = 'id';

    /**
     * 意见反馈
     * @param int $uid
     * @param array $data
     * @return int
     */
    public function saveData(int $uid, array $data): int
    {
        try
        {
            $fqId = $this->insertGetId($data);

            (new ZlFeedbackQuestionTags())->feedbackQuestionTagAdd($fqId, $data['question']);

            $this->listDataAdd($uid, [$fqId => $fqId]);

            return $fqId;
        }
        catch (\Exception $e)
        {
            Log::write('意见反馈失败;错误信息:' . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」", 'error', true);
            return 0;
        }
    }

    /**
     * 获取历史意见反馈信息
     * @param int $uid
     * @return array
     * @throws \Exception
     */
    public function getFeedbackList(int $uid): array
    {
        $data = $this->getListPage($uid);

        $systemAvatar = Env::get('host.photo') . config('feedback.admin_avatar');
        if (isset($data['data']))
        {
            $d = [];
            foreach ($data['data'] as $item)
            {
                $fqId = (int)$item['id'];
                $relayInfo = (new ZlFeedbackQuestionInfo())->getReplyList($fqId, 1, 1);
                $des = '';
                $time = date('Y-m-d', $item['create_time']);
                if ($relayInfo['data'])
                {
                    $relayInfoItem = current($relayInfo['data']);
                    $time = $relayInfoItem['create_time'];
                    if ((int)$relayInfoItem['content_type'] === 1)
                    {
                        $des = $relayInfoItem['content'];
                    } else
                    {
                        $des = '[图片]';
                    }
                }

                $d[] = [
                    'fid' => $fqId,
                    'title' => $item['tname'],
                    'des' => $des,
                    'avatar' => $systemAvatar,
                    'time' => $time,   // 最新回复时间
                    'is_new_reply' => (int)$item['user_has_msg']
                ];
            }
            $data['data'] = $d;
        }

        return $data;
    }

    /**
     * 重写数据时获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $this->whereIn('q.id', $ids);
            } else
            {
                $this->where(['q.uid' => $type[0]]);
            }
            $data = $this->alias('q')
                ->join('wechat_backup_07_18_14_43_00.zl_feedback_tag t', 'q.tid=t.id')->order("q.id {$sortType}")
                ->column('q.uid,q.tid,t.name tname,q.question,q.question_img,q.app_version,q.phone_type,q.contact,q.phone_system,q.phone_info,q.last_reply_time,q.user_has_msg,q.admin_has_msg,q.create_time,q.update_time', 'q.id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    /**
     * 未开启缓存从数据库获取分页数据
     * @param array $type 分页数据状态
     * @param string $sortType 排序方式
     * @return array
     */
    public function getPaginateInData($type, $sortType)
    {
        try
        {
            $data = $this->alias('q')
                ->join('wechat_backup_07_18_14_43_00.zl_feedback_tag t', 'q.tid=t.id')->where(['q.uid' => $type[0]])->order("q.id {$sortType}")
                ->field('q.id,q.uid,q.tid,t.name tname,q.question,q.question_img,q.app_version,q.phone_type,q.contact,q.phone_system,q.phone_info,q.last_reply_time,q.user_has_msg,q.admin_has_msg,q.create_time,q.update_time')
                ->paginate()->toArray();

            return $data;
        }
        catch (\Exception $e)
        {
            return [];
        }
    }

    /**
     * 获取用户是否有新消息
     * @param int $uid
     * @return bool
     * @throws \Exception
     */
    public function getUserHasNewMsg(int $uid): bool
    {
        $newMsgFqids = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)
            ->setCacheKeyDetail('new_msg_question', $uid)
            ->setListCacheTime(43200)   // 设置半天的过期时间
            ->setPage(-1)
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($uid)
            {
                try
                {
                    $ids = $this->where(['uid' => $uid, 'user_has_msg' => 1])->column('id');

                    if ($isCache)
                    {
                        $data = [];
                        foreach ($ids as $idItem)
                        {
                            $data[$idItem] = ['id' => $idItem];
                        }
                        return $data;
                    }
                    return $ids;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'id', 0, 'new_msg_question');

        return $newMsgFqids['total'] > 0;
    }

    /**
     * 删除未读新消息标记
     * @param int $uid
     * @param int $fqid
     * @throws \Exception
     */
    public function newMsgdel(int $uid, int $fqid)
    {
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)
            ->setCacheKeyDetail('new_msg_question', $uid)
            ->delJudge($fqid, 'new_msg_question');
    }
}
